<template>
  <div id="SafetyAppraisal">
    <div class="top">
      <img v-if="row.NODE_GUID === '{27EE0E9F-607B-4D25-8934-3693F950C095}'" style="margin: 0 auto" class="imgtop" src="https://nfzjszlb.jst.zj.gov.cn/serverfile/zheliban/icon/ZLJ/fgx2.png" />
      <img v-else style="margin: 0 auto" class="imgtop" src="https://nfzjszlb.jst.zj.gov.cn/serverfile/zheliban/icon/ZLJ/fgx.png" />
      <p>
        <span style="width: 125px;display: inline-block;text-align: left">房屋安全鉴定</span>
        <span style="width: 150px;display: inline-block;text-align: right">复核鉴定</span>
      </p>
    </div>
    <div class="content">
      <van-form validate-first :class="{smallFontSize:showEdition,mediumFontSize:!showEdition}">
        <div class="inputWrap">
          <van-field readonly v-model="formData.SQR" placeholder="请输入户主姓名" label="户主姓名" :rules="[{ required: true, message: '请填写户主姓名' }]" />
        </div>
        <div class="inputWrap">
          <van-field readonly v-model="formData.ZJH" label="身份证号码" name="validator" @blur.native.capture="handleGetCityData" placeholder="身份证号码" :rules="[{ validator, message: '请输入正确身份证号码' }]" />
        </div>
        <div class="inputWrap">
          <van-field readonly placeholder="请输入手机号码" v-model="formData.SJH" label="手机号" :rules="[
              { required: true, message: '请填写您的手机号码！' },
              { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式错误！'}
            ]" name="pattern" />
        </div>
        <div class="inputWrap">
          <van-field readonly clickable name="picker" :value="formData.SCITY | inUseName1(CityColumns)" label="所属市" placeholder="请选择所属市" :rules="[{ required: true, message: '请选择所属市' }]" />
        </div>
        <div class="inputWrap">
          <van-field readonly clickable name="picker" :value="formData.XCITY | inUseName1(XianColumns)" label="所属县(区)" placeholder="请选择所属县(区)" />
        </div>
        <div class="inputWrap">
          <van-field readonly clickable name="picker" :value="formData.ZCITY | inUseName1(TownColumns)" label="所属镇" placeholder="请选择所属镇" />
        </div>
        <div class="inputWrap">
          <van-field readonly clickable name="picker" :value="formData.CCITY | inUseName1(CunColumns)" label="所属村" placeholder="请选择所属村" />
        </div>
        <div class="inputWrap">
          <van-field readonly v-model="formData.FWDZ" label="房屋地址" placeholder="请输入房屋地址" />
        </div>
        <div class="inputWrap">
          <van-field readonly v-model="formData.CS" label="建筑层数" placeholder="请输入建筑层数" />
        </div>
        <div class="inputWrap">
          <van-field readonly v-model="formData.NF" label="建造年份" placeholder="请输入建造年份" />
        </div>
        <div class="inputWrap">
          <van-field readonly v-model="formData.F_JDJG" label="鉴定机构" placeholder="请输入鉴定机构" />
        </div>
      </van-form>
      <p class="subTitle">
        <span class="line"></span>鉴定信息
      </p>
      <van-form validate-first :class="{smallFontSize:showEdition,mediumFontSize:!showEdition}">
        <div class="inputWrap">
          <span style="color: #FF0000;">*</span>
          <van-field clickable readonly :value="formDataJD.JDLX | inUseName(ENUM.JDLXARR)" label="鉴定类型" placeholder="请选择鉴定类型" @click="ENUM.JDLX = true" />
          <van-popup v-model="ENUM.JDLX" position="bottom" get-container="#popup">
            <van-picker show-toolbar :columns="ENUM.JDLXARR" value-key="DICNAME" @confirm="confirmJDLX" @cancel="ENUM.JDLX = false" />
          </van-popup>
        </div>
        <div class="inputWrap">
          <span style="color: #FF0000;">*</span>
          <van-field v-model="formDataJD.JDBGBH" label="鉴定报告编号" placeholder="请输入鉴定报告编号" />
        </div>
        <div class="inputWrap">
          <span style="color: #FF0000;">*</span>
          <van-field clickable readonly :value="formDataJD.JDDJ | inUseName(ENUM.JDDJARR)" label="鉴定等级" placeholder="请选择鉴定等级" @click="ENUM.JDDJ = true" />
          <van-popup v-model="ENUM.JDDJ" position="bottom" get-container="#popup">
            <van-picker show-toolbar :columns="ENUM.JDDJARR" value-key="DICNAME" @confirm="confirmJDDJ" @cancel="ENUM.JDDJ = false" />
          </van-popup>
        </div>
        <div class="inputWrap">
          <span style="color: #FF0000;">*</span>
          <van-field readonly clickable name="datetimePicker" :value="formDataJD.JDSJ" label="鉴定时间" placeholder="请选择鉴定时间" @click="showPickerq = true" />
          <van-popup v-model="showPickerq" position="bottom" get-container="#popup">
            <van-datetime-picker v-model="currentDate" type="date" title="选择年月日" @cancel="showPickerq = false" @confirm="onConfirmRQ" />
          </van-popup>
        </div>
        <div class="inputWrap">
          <span style="color: #FF0000;">*</span>
          <van-field label="上传人" v-model="formDataJD.SCR" placeholder="请输入上传人" />
        </div>
        <p class="title">备注</p>
        <div class="inputWrap">
          <van-field v-model="formDataJD.BZ" autosize type="textarea" placeholder="请输入备注" label />
        </div>
      </van-form>
      <div v-for="(item,index) in file" :key="index">
        <p class="title">
          <span style="color: #FF0000;">*</span>
          {{item.name}}
        </p>
        <van-uploader @click-upload="getList(item)" @click-preview="lookFile" :after-read="afterRead" :before-delete="delectFile" v-model="item.fileList" accept=".jpg,.gif,.png,.jpeg,.txt,.pdf,.doc,.docx,.xls,.xlsx" multiple />
      </div>
    </div>
    <div class="footer">
      <div class="bottomBtn" @click="getinsertDataView">提交</div>
    </div>
  </div>
</template>

<script>
import { QuerySignCallback, dataServerOpenDataView, GetFileData, FileServerUpload, DelectFile,dataTransFilePreview,FileServerProxy } from '@/utils/api'
export default {
  name: 'SafetyAppraisal',
  data() {
    return {
      showEdition: false,
      row: {},
      rowGuid: '',
      dataguid: '9788c08d-3d96-4f0d-85da-d233094abcf6',
      formData: {},
      formDataJD: {
        CS: '',
        NF: '',
        SCITY: '',
        XCITY: '',
        ZCITY: '',
        CCITY: '',
        JDLX: '',
        JDDJ: '',
        JDSJ: '',
        BZ: '',
        JDBGBH: '',
        OPTYPE: 1,
        SCR: JSON.parse(window.localStorage.getItem('userName')).userName
      },
      currentDate: new Date(),
      CityColumns: [],
      XianColumns: [],
      TownColumns: [],
      CunColumns: [],
      showPickerq: false,
      ENUM: {
        JDLXARR: [],
        JDLX: false,
        JDDJARR: [],
        JDDJ: false
      },
      file: [
        {
          name: '鉴定报告',
          groupGuid: '88d711ba-870c-40f2-a81d-71df8caeefd4',
          fileList: []
        },
        {
          name: '房屋照片',
          groupGuid: '8188d4d5-0898-44b9-b7f9-4f84dfb58f11',
          fileList: []
        }
      ],
    }
  },
  watch: {},
  filters: {
    inUseName: function (msg, data) {
      let name = ''
      data.forEach(item => {
        if (item.DICID == msg) {
          name = item.DICNAME
        }
      })
      return name
    },
    inUseName1: function (msg, data) {
      let name = ''
      data.forEach(item => {
        if (item.CITYCODE == msg) {
          name = item.CITYNAME
        }
      })
      return name
    }
  },
  methods: {
    validator(val) {
      var idcardReg =
        /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/
      return idcardReg.test(val)
    },
    getCityOpenDataView: async function () {
      this.CityColumns = []
      let dataGuid = 'e9c98787-4966-4365-80b0-c1cc678c6f85'
      let token = window.localStorage.getItem('token')
      let params = {
        accessCode: "688bd3883572440a859dfd8ba9194e7b",

        params: {
          dataguid: dataGuid,
          searchObject: JSON.stringify([]),
          token: token,
        },
      };
      const res = await QuerySignCallback(params);
      this.CityColumns = JSON.parse(res.data.data).Data
    },
    getXianOpenDataView: async function (data) {
      this.XianColumns = []
      let dataGuid = '77fdf2b0-0eb5-4243-a0a4-6185299ccd34'
      let searchObject = JSON.stringify([{ field: 'pid', value: data, operator: '=' }])
      let token = window.localStorage.getItem('token')
      let params = {
        accessCode: "688bd3883572440a859dfd8ba9194e7b",

        params: {
          dataguid: dataGuid,
          searchObject: searchObject,
          token: token,
        },
      };
      const res = await QuerySignCallback(params);
      this.XianColumns = JSON.parse(res.data.data).Data
    },
    getTownOpenDataView: async function (data) {
      this.TownColumns = []
      let dataGuid = '24d07248-ba49-4b82-9029-b5eccaff179d'
      let searchObject = JSON.stringify([{ field: 'pid', value: data, operator: '=' }])
      let token = window.localStorage.getItem('token')
      let params = {
        accessCode: "688bd3883572440a859dfd8ba9194e7b",

        params: {
          dataguid: dataGuid,
          searchObject: searchObject,
          token: token,
        },
      };
      const res = await QuerySignCallback(params);
      this.TownColumns = JSON.parse(res.data.data).Data
    },
    getCunOpenDataView: async function (data) {
      this.CunColumns = []
      let dataGuid = 'd3aaed7c-84ee-4de3-b70e-07fe188cdc8e'
      let searchObject = JSON.stringify([{ field: 'pid', value: data, operator: '=' }])
      let token = window.localStorage.getItem('token')
      let params = {
        accessCode: "688bd3883572440a859dfd8ba9194e7b",

        params: {
          dataguid: dataGuid,
          searchObject: searchObject,
          token: token,
        },
      };
      const res = await QuerySignCallback(params);
      this.CunColumns = JSON.parse(res.data.data).Data
    },
    getEnum: async function (viewID) {
      let token = window.localStorage.getItem('token')
      let params = {
        accessCode: "688bd3883572440a859dfd8ba9194e7b",

        params: {
          dataguid: viewID,
          searchObject: JSON.stringify([]),
          token: token,
        },
      };
      const res = await QuerySignCallback(params);
      let data = JSON.parse(res.data.data).Data
      switch (viewID) {
        case 'b15c9597-ccb8-435c-b43d-06fe30fc0e08':
          this.ENUM.JDLXARR = data
          break
        case 'c7007467-d12c-4b87-948e-aa58b2df2131':
          this.ENUM.JDDJARR = data
          break
        default:
          break
      }
    },
    onConfirmRQ(val) {
      let year = val.getFullYear()
      let month = val.getMonth() + 1
      let day = val.getDate()
      let hour = val.getHours()
      let minute = val.getMinutes()
      if (month >= 1 && month <= 9) {
        month = `0${month}`
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`
      }
      this.className = 'timeClass'
      this.formDataJD.JDSJ = `${year}-${month}-${day}`
      this.showPickerq = false
    },
    getList(item) {
      this.groupGuids = item.groupGuid
    },
    //
    confirmJDLX(val) {
      this.formDataJD.JDLX = val.DICID
      this.ENUM.JDLX = false
    },
    confirmJDDJ(val) {
      this.formDataJD.JDDJ = val.DICID
      this.ENUM.JDDJ = false
    },
    //获取相关材料
    getFile: async function () {
      let groupGuid = []
      this.file.forEach(item => {
        groupGuid.push(item.groupGuid)
      })
      const res1 = await GetFileData({
        groupGuid: groupGuid.join(','),
        toRowGuid: this.rowGuid
      })
      if (res1.data.FilesInfo.length > 0) {
        res1.data.FilesInfo.forEach(element => {
          this.file.forEach(item => {
            if (element.GROUPGUID == item.groupGuid) {
              element['isImage'] = item.name == '鉴定报告' ? false : true
              element['file'] = {
                name: element.FILENAME
              }
              this.getFileUrl(element, item);
              // element['url'] =
              //   window.g.BaseURL +
              //   'FileServer/api/Preview?token=' +
              //   window.localStorage.getItem('token') +
              //   '&' +
              //   'fileGuid=' +
              //   encodeURIComponent(element.ROW_GUID)
              // item.fileList.push(element)
            }
          })
        })
      }
    },
    //相关材料
    afterRead(file) {
      // 此时可以自行将文件上传至服务器
      this.getFileServerUpload(file.file)
    },
      delectFile: async function (file) {
      let fileguid = "";
      if (file.ROW_GUID) {
        fileguid = file.ROW_GUID;
      } else {
        fileguid = this.fileGuid;
      }
      if (fileguid) {
        let params = {
          accessCode: "ce9b691634de4ebca68dc5bb638d07f4",
          cityCode: window.localStorage.getItem("citycode")
            ? window.localStorage.getItem("citycode")
            : "441300000000",
          params: {
            fileGuid: fileguid,
            token: window.localStorage.getItem("token"),
          },
        };
        const res = await FileServerProxy(params);
        let data = JSON.parse(res.data.data).Success;
        if (data) {
          this.$toast.success("删除成功!");
        }
      }
    },
    // delectFile: async function (file) {
    //   if (file.ROW_GUID) {
    //     const res = await DelectFile({
    //       fileGuid: file.ROW_GUID,
    //       token: window.localStorage.getItem('token')
    //     })
    //     if (res.data.Success) {
    //       this.$toast.success('成功!')
    //     } else {
    //       this.$toast.fail(res.data.Msg)
    //     }
    //   }
    // },
    getFileServerUpload: async function (file) {
      let formData = new FormData()
      // if (file instanceof Array) {
      //   file.forEach(item => {
      //     formData.append('file', item.file)
      //   })
      // } else {
      //   formData.append('file', file.file)
      // }
      let _this = this;
      formData.append('file', file)
      formData.append('toRowGuid', this.rowGuid)
      formData.append('groupGuid', this.groupGuids)
      formData.append('token', window.localStorage.getItem('token'))
      const res = await FileServerUpload(formData)
      if (res.data.Success == true) {
        this.$toast.success('上传成功!')
        if (this.groupGuids == "88d711ba-870c-40f2-a81d-71df8caeefd4") {
          res.data.FileList.forEach((item, index) => {
            item['isImage'] = false
            item['file'] = {
              name: item.FILENAME
            }
            item['url'] =
              window.g.BaseURL +
              'FileServer/api/Preview?token=' +
              window.localStorage.getItem('token') +
              '&' +
              'fileGuid=' +
              encodeURIComponent(item.FILEGUID)
            _this.file[0].fileList[_this.file[0].fileList.length - 1 - index] = item
            _this.$forceUpdate()
          })
        }
        // this.$notify({ type: 'success', message: '上传成功!' });        // this.$notify({ type: 'success', message: '上传成功!' });
      }
    },
    //
    lookFile(item) {
      if (itme.isImage == false) {
        if (ZWJSBridge) {
          ZWJSBridge.openLink({
            "url": item.url
          }).then(res => {
          }).catch(err => {
          })
        }
      }
    },
    //获取附件文件流
    getFileUrl: async function (element, item) {
      let formData = new FormData();
      formData.append("accessCode", "98bcf528966e48ce896a8b3fd02d45d5");
      formData.append(
        "cityCode",
        window.localStorage.getItem("citycode")
          ? window.localStorage.getItem("citycode")
          : "441300000000"
      );
      formData.append(
        "paramStr",
        JSON.stringify({
          fileGuid: element.ROW_GUID,
        })
      );
      let response = await dataTransFilePreview(formData);
      if (response) {
        var img = new Blob([new Int8Array(response.data, 0)], {
          type: response.headers["content-type"],
        }); //type类型可自定义
        element["isImage"] = true;
        element["url"] = window.URL.createObjectURL(img);
        item.fileList.push(element);
      }
    },
    getinsertDataView: async function () {
      let me = this
      let add = true
      me.file.forEach((item, index) => {
        if (item.fileList.length == 0) {
          add = false
          me.$toast.success('请上传附件！')
        }
      })
      if (add) {
        if (me.formDataJD.JDLX && me.formDataJD.JDDJ && me.formDataJD.JDSJ && me.formDataJD.JDBGBH && me.formDataJD.SCR) {
          let accessCode = '77ad6c1591e54d4fbc45ecc90374a2a2'
          if (!me.formDataJD.ROW_GUID) {
            accessCode = '0fb3f6123d1b4fe6851c99532c463f6f'
            me.formDataJD['ROW_GUID'] = me.rowGuid
            me.formDataJD['TO_ROW_GUID'] = me.row.ROW_GUID
            me.formDataJD['FWDZ'] = me.formData.FWDZ
            me.formDataJD['CS'] = me.formData.CS
            me.formDataJD['NF'] = me.formData.NF
            me.formDataJD['JDJG'] = me.formData.JDJG
            me.formDataJD['SCITY'] = me.formData.SCITY
            me.formDataJD['XCITY'] = me.formData.XCITY
            me.formDataJD['ZCITY'] = me.formData.ZCITY
            me.formDataJD['CCITY'] = me.formData.CCITY
            me.formDataJD['F_JDJG'] = me.formData.F_JDJG
          }
          let params = {
            dataGuid: me.dataguid,
            strParams: JSON.stringify([me.formDataJD]),
            token: window.localStorage.getItem('token')
          }
          let params1 = {
            accessCode: accessCode,

            cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000',
            params: params
          }
          const res = await QuerySignCallback(params1)
          if (eval('(' + res.data.data + ')').Success == true) {
            me.$toast.success('成功！')
            this.$router.push({
              path: '/TreeSelectAutoSend',
              query: { data: this.row, type: "房屋安全鉴定",list:true }
            })
          } else {
            me.$toast.fail(res.data.msg)
          }
        } else {
          me.$toast.success('请输入必填项！')
        }
      }
    },
    getData: async function () {
      //调用存储过程查回基本信息
      let paerauto = {
        procName: 'up_housesecurity',
        dtParams: JSON.stringify([{ I_USERID: "'" + this.row.ROW_GUID + "'", I_TYPE: 1 }]),
        token: window.localStorage.getItem('token')
      }
      let procNameAuto = {
        accessCode: '69db6bece3a7480592e2ec753d1e335e',

        cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000',
        params: paerauto
      }
      const res = await QuerySignCallback(procNameAuto)
      let data = eval('(' + res.data.data + ')').Data
      if (data.length > 0) {
        this.formData = data[0]
      } else {
        this.formData = this.row;
      }
      //查询鉴定信息
      let params = {
        dataguid: this.dataguid,
        searchObject: JSON.stringify([{ field: 'TO_ROW_GUID', value: this.row.ROW_GUID, link: 'OR', operator: '=' }]),
        token: window.localStorage.getItem('token')
      }
      let params1 = {
        accessCode: '688bd3883572440a859dfd8ba9194e7b',

        params: params
      }
      const res1 = await QuerySignCallback(params1)
      let data1 = eval('(' + res1.data.data + ')').Data
      if (data1.length > 0) {
        this.formDataJD = data1[0]
        this.rowGuid = this.formDataJD.ROW_GUID
        this.getFile()
      } else {
        this.rowGuid = this.newGuid()
        this.formDataJD.SCR = JSON.parse(window.localStorage.getItem('userName')).userName
      }
      this.getXianOpenDataView(this.formData.SCITY)
      this.getTownOpenDataView(this.formData.XCITY)
      this.getCunOpenDataView(this.formData.ZCITY)
    }
  },
  mounted() {
    this.row = JSON.parse(this.$route.query.data)
    //获取当前时间
     var date = new Date()
     var year = date.getFullYear() //获取当前年份
     var mon = date.getMonth() + 1 //获取当前月份
     var da = date.getDate() //获取当前日
     var d = document.getElementById('Date')
     var time1 = year + '-' + mon + '-' + da
     this.formData.JDSJ = time1
    this.showEdition = this.$store.state.Edition
    this.getEnum('b15c9597-ccb8-435c-b43d-06fe30fc0e08')
    this.getEnum('c7007467-d12c-4b87-948e-aa58b2df2131')
    this.getData()
    this.getCityOpenDataView()
    if (this.showEdition) {
      $('#SafetyAppraisal .van-field__control').css('fontSize', '16px !important')
      $('#SafetyAppraisal .van-cell').css('fontSize', '16px !important')
    } else {
      $('#SafetyAppraisal .van-field__control').css('fontSize', '20px !important')
      $('#SafetyAppraisal .van-cell').css('fontSize', '20px !important')
    }
    if (ZWJSBridge) {
      ZWJSBridge.setTitle({
        title: '房屋安全鉴定'
      })
        .then(res => {
        })
        .catch(err => {
        })
    }
  }
}
</script>
<style scoped lang="scss">
#SafetyAppraisal {
  height: 100vh;
  .top {
    height: 80px;
    background: #ffffff;
    padding-top: 25px;
    text-align: center;
    .imgtop {
      width: 60%;
      margin: 0 auto;
    }
    .origin {
      width: 22px;
      height: 22px;
      background: #007aff;
      border-radius: 50%;
      display: inline-block;
    }
  }
  .content {
    width: 100%;
    height: calc(100% - 140px);
    overflow: auto;
    background: #ffffff;
    padding: 10px;
    .subTitle {
      color: #3f8ffc;
      height: 40px;
      line-height: 40px;
      font-size: 16px;
      //   .line {
      //     width: 6px;
      //     height: 26px;
      //     background: #3f8ffc;
      //     display: inline-block;
      //     margin-right: 10px;
      //   }
    }
    .title {
      color: black;
      font-size: 16px;
      line-height: 40px;
    }
    .inputWrap {
      display: flex;
      justify-content: center;
      align-items: center;
      border-bottom: 1px solid #d2d2d2;
    }
    .van-cell {
      padding: 10px 0;
    }
  }
  .footer {
    padding: 0 10px;
    text-align: center;
    .bottomBtn {
      height: 50px;
      background: #007aff;
      line-height: 50px;
      text-align: center;
      color: #ffffff;
      font-weight: bold;
    }
  }
}
</style>
<style lang="scss">
#SafetyAppraisal {
  .van-field__label {
    width: auto !important;
  }
  .mediumFontSize {
    .van-field__label {
      font-size: 20px;
    }
  }
  .el-input__inner {
    /*font-size: 16px;*/
    text-align: right;
    border: none;
  }
  .van-cell:not(:last-child)::after {
    left: 0;
    // border-bottom: 1px solid rgb(210, 210, 210);
  }
  .van-cell::after {
    border-bottom: none;
  }
  .van-cell {
    padding: 10px 0;
    font-size: 16px;
  }
  .van-field__control {
    text-align: right;
  }
  textarea {
    text-align: left !important;
  }
  .van-field__label {
    color: black !important;
    letter-spacing: 1px;
  }
  .van-cell {
    color: black;
  }
}
</style>
